//
//  ViewController.m
//  wdawdawdw
//
//  Created by 吕超 on 16/10/28.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
#import "LXModel.h"
#import "LXTableViewCell.h"
#import "ShouCangVController.h"
#import "DataBase.h"


#define selfPingMuWidth [UIScreen mainScreen].bounds.size.width
#define selfPingMuHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,LXTableViewCellDelegate>

//  主tableView
@property (nonatomic, strong)UITableView *mainTableView;

//  数据 数组
@property (nonatomic, strong)NSMutableArray *MyArray;

//全选 btn
@property (nonatomic, strong)UIButton *allSelectBtn;

//显示金额  总和
@property (nonatomic, strong)UILabel *zongHeLabel;

//  滚动背景
@property (nonatomic, strong)UIScrollView *backScrollView;

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,selfPingMuWidth, selfPingMuHeight - 64 - 60 )];
    
    _mainTableView.delegate = self;
    
    _mainTableView.dataSource = self;
    
    //  cell 高    可以确定cell 高度时 这么写可以 提高执行效率
    _mainTableView.rowHeight =  230;
    
    //注册
    [_mainTableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:@"111"];

    [self requestData];
    
    [self.view addSubview:self.backScrollView];
    
    [self.backScrollView addSubview:self.mainTableView];
    
    
    
    // 全选收藏按钮上面的线
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backScrollView.frame) + 5, selfPingMuWidth, 3)];
    
    line.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:line];
    
    
    //全选按钮
    _allSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _allSelectBtn.backgroundColor = [UIColor redColor];
    
    _allSelectBtn.frame = CGRectMake(20,CGRectGetMaxY(line.frame) + 7 , 70 , 40);
    
    [_allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];
    
    [_allSelectBtn addTarget:self action:@selector(allSelectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _allSelectBtn.selected = YES;
    [self.view addSubview: self.allSelectBtn];
    
    
    
    
    // 收藏  按钮
    UIButton  *reckonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    reckonBtn.backgroundColor = [UIColor redColor];
    
    reckonBtn.frame = CGRectMake(CGRectGetMaxX(self.allSelectBtn.frame) + 20,CGRectGetMaxY(line.frame) + 7 , 70 , 40);
    
    [reckonBtn setTitle:@"收藏" forState:UIControlStateNormal];
    
    [reckonBtn addTarget:self action:@selector(reckonButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:reckonBtn];

    
    
    _zongHeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(reckonBtn.frame) + 20, CGRectGetMinY(reckonBtn.frame) , selfPingMuWidth - CGRectGetMaxX(reckonBtn.frame) - 40, 40)];
    
    _zongHeLabel.textAlignment = NSTextAlignmentCenter;
    _zongHeLabel.backgroundColor = [UIColor whiteColor];
    _zongHeLabel.textColor = [UIColor blackColor];
    _zongHeLabel.text = @"0";
    _zongHeLabel.font = [UIFont systemFontOfSize:19];
    [self.view addSubview:self.zongHeLabel];
    
    
    //   tableView 添加手势
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    
    [self.mainTableView addGestureRecognizer:tapGestureRecognizer];
    
    
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];

}



- (void)requestData{
    
     __weak typeof(self) WeakSelf = self;
    
    //  网络请求
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://c.3g.163.com/newstopic/list/expert/%d-%d.html",0,10];
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    
    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        

        [WeakSelf.MyArray removeAllObjects];
        
        NSMutableDictionary *dict = [NSJSONSerialization  JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //解析出来的关键字
        NSArray *rootArray = dict[@"data"][@"expertList"];
        
        for (NSDictionary *smallDict in rootArray) {
            LXModel  *model = [[LXModel alloc] init];
            [model setValuesForKeysWithDictionary:smallDict];
      
            [WeakSelf.MyArray addObject:model];
        }
        
        //刷新数据
        [self.mainTableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.MyArray.count;
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"111"];
    
    if(cell == nil){
        cell = [[LXTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"111"];
    }
    cell.delegate = self;
    
    [cell.numberTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    // cell 上 传递  tag
    cell.selectBtn.tag = indexPath.row;

    cell.rightButton.tag = indexPath.row;

    cell.leftButton.tag = indexPath.row;
    
    LXModel *model = self.MyArray[indexPath.row];
    

    [cell setCellModel:model];
    
    cell.selectBtn.selected = model.isBtnSelect;
    
    cell.PictureImage.image = [UIImage imageWithData:model.picture];
    
    if (cell.selectBtn.selected == YES){
        
        [cell.selectBtn setImage:[UIImage imageNamed:@"选中"] forState:(UIControlStateNormal)];
    }else if(cell.selectBtn.selected == NO){
        [cell.selectBtn setImage:[UIImage imageNamed:@"未选中"] forState:(UIControlStateNormal)];
    }
    
    if (model.number == nil || model.number <= 0) {
        cell.numberTF.text = @"";
        cell.numberTF.placeholder = @"0";
    }else if(model.number != nil){
        cell.numberTF.text = model.number;
    }
    
    //  价格
    cell.priceLabel.text = [NSString stringWithFormat:@"%ld",model.DanGeJiaGe];
    
    cell.numberTF.delegate = self;
    
    // 修改占位符  颜色
    [cell.numberTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    return  cell;
}


// TextField 输入完成
- (void)textFieldDidEndEditing:(UITextField *)textField{
    

    if (textField.text.length == 0 ||  [textField.text isEqualToString:@"0"]){
        textField.text = @"";
        textField.placeholder = @"0";

        LXTableViewCell *cell = (LXTableViewCell*)[textField superview];
        
        // 获取cell indexpath
        NSIndexPath *indexPath = [self.mainTableView indexPathForCell:cell];
        
        LXModel *model =  self.MyArray[indexPath.row];
        
        LXModel *tempModel = [[LXModel alloc]init];
        
        tempModel.alias = model.alias;
        
        tempModel.isBtnSelect = NO;
        
        //替换
        [self.MyArray replaceObjectAtIndex:indexPath.row withObject:tempModel];

        _zongHeLabel.text = [self ZongHeJiSuan:self.MyArray];
        
         [self.mainTableView reloadData];

    } else {
    
        LXTableViewCell *cell = (LXTableViewCell*)[textField superview];
        
        // 获取cell indexpath
        NSIndexPath *indexPath = [self.mainTableView indexPathForCell:cell];
        
        LXModel *model =  self.MyArray[indexPath.row];
        
        LXModel *tempModel = [[LXModel alloc]init];
        
        tempModel.alias = model.alias;
        
        tempModel.isBtnSelect = YES;
        
        tempModel.number = textField.text;
        
        //替换
        [self.MyArray replaceObjectAtIndex:indexPath.row withObject:tempModel];

        _zongHeLabel.text = [self ZongHeJiSuan:self.MyArray];
        
         [self.mainTableView reloadData];
    }
}


#pragma mark  ====   收藏按钮点击方法
- (void)reckonButtonAction{

    // 打开数据库
    [DataBase ShareDataBase];
    
    ShouCangVController *sc = [[ShouCangVController alloc]init];
    
    for (int i = 0 ; i < self.MyArray.count ; i++){
        LXModel *model = self.MyArray[i];
    
        if (model.isBtnSelect == YES){

        [[DataBase ShareDataBase]addDataBase:model];
            
        }
    }
    [self.navigationController pushViewController:sc animated:YES];
}




#pragma mark =====  全选方法
- (void)allSelectBtnAction:(UIButton *)btn{
    //  之前有数值的
    NSInteger a = 0;
    //   之前没有数值的
    NSInteger b = 0;
    
    for (int i = 0 ; i < self.MyArray.count ; i++){

        LXModel *model =  self.MyArray[i];

        LXModel *tempModel = [[LXModel alloc]init];
        
        tempModel.alias = model.alias;
        
        if (btn.selected == YES){

            tempModel.isBtnSelect = YES;

            NSInteger  tempNumber = [model.number integerValue];
      
            if (tempNumber == 0){
                b++ ;
               tempModel.number = [NSString stringWithFormat:@"1"];
            } else  {
                tempModel.number = model.number;
                
                a = a + tempNumber;
            }
            
            tempNumber = b + a;
            
            _zongHeLabel.text = [NSString stringWithFormat:@"%ld",(b + a) * tempModel.DanGeJiaGe];

        } else {
            // 取消 全选
            
            tempModel.isBtnSelect = NO;
            
            NSInteger  tempNumber = 0;

            tempModel.number = [NSString stringWithFormat:@"%ld",tempNumber];
            _zongHeLabel.text = @"0";
        }

        
        //替换
        [self.MyArray replaceObjectAtIndex:i withObject:tempModel];

    }
    
       [self.mainTableView reloadData];
    
    // 点击  切换  button   状态
    if (btn.selected == YES){
        btn.selected = NO;
    
    } else {
        btn.selected = YES;
    }
    
}



#pragma mark ==== cell代理方法
//  选中  代理
- (void)selectAtIndex:(NSInteger)row{
    
    LXModel *model =  self.MyArray[row];
    
    LXModel *tempModel = [[LXModel alloc]init];

    tempModel.alias = model.alias;
    
    
    if (model.isBtnSelect == YES){
        
        //  取消选中状态  直接清0
        NSInteger  tempNumber = [tempModel.number integerValue];
        if (tempNumber == 0){
            tempModel.number = @"";
        }
        
        tempModel.isBtnSelect = NO;
        
    } else if (model.isBtnSelect == NO){
        
        tempModel.isBtnSelect = YES;
  
        NSInteger  tempNumber = [tempModel.number integerValue];
        
        //  选中加一
        tempNumber++;
        
        tempModel.number = [NSString stringWithFormat:@"%ld",tempNumber];
    }

    //替换
    [self.MyArray replaceObjectAtIndex:row withObject:tempModel];
    
    _zongHeLabel.text = [self ZongHeJiSuan:self.MyArray];
    
    [self.mainTableView reloadData];
}



//   添加的  btn  代理
- (void)addButtonDelegate:(NSInteger)row{
    
    
    LXModel *model =  self.MyArray[row];
    
    LXModel *tempModel = [[LXModel alloc]init];
    
    tempModel.alias = model.alias;

    tempModel.number = model.number;
    

    //选中按钮  选中状态
    tempModel.isBtnSelect = YES;
    
    
    NSInteger  tempNumber = [tempModel.number integerValue];
    tempNumber++;
    tempModel.number = [NSString stringWithFormat:@"%ld",tempNumber];
  
    //   替换
    [self.MyArray replaceObjectAtIndex:row withObject:tempModel];
    
  
    _zongHeLabel.text = [self ZongHeJiSuan:self.MyArray];
    
    
    [self.mainTableView reloadData];
}



// 减号  代理  方法
- (void)jianButtonDelegate:(NSInteger)row{

    LXModel *model =  self.MyArray[row];
    
    LXModel *tempModel = [[LXModel alloc]init];
    
    tempModel.alias = model.alias;
    
    tempModel.number = model.number;
    
    
    NSInteger reduce  = [tempModel.number integerValue];
    reduce--;
    tempModel.isBtnSelect = YES;
   
        if (reduce <= 0 ) {
            reduce = 0 ;
          tempModel.isBtnSelect = NO;
        }
    
    tempModel.number = [NSString stringWithFormat:@"%ld",reduce];
    //替换
    [self.MyArray replaceObjectAtIndex:row withObject:tempModel];
    
    _zongHeLabel.text = [self ZongHeJiSuan:self.MyArray];
    
    [self.mainTableView reloadData];
}




#pragma mark ===== 总和计算
- (NSString *)ZongHeJiSuan:(NSMutableArray *)arrary{
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < arrary.count; i++) {
        LXModel *model = arrary[i];
      
        [arr addObject:[NSString stringWithFormat:@"%ld",model.DanGeJiaGe * [model.number integerValue]]];
        
    }
    // 数组之和
    NSNumber *sum = [arr valueForKeyPath:@"@sum.self"];
    
    return  [NSString stringWithFormat:@"%@",sum];
}




#pragma mark  ====   监听  tf 变化  正则表达式
- (void)textFieldDidChange:(UITextField *)tf{
    
    if ([self checkForNumber:tf.text] ){
        
    } else {
        // 防止崩溃
        if (tf.text.length > 0){
            //  不匹配删掉  字符串最后一位
            tf.text = [tf.text substringToIndex:tf.text.length - 1];
        }
    }
}


//   只能输入数字  开头不能为0
- (BOOL)checkForNumber:(NSString *)number{
    //转意符  \d  \\d
    NSString *regEx = @"^[1-9]\\d*$";
    return [self baseCheckForRegEx:regEx data:number];
}


// 检测 正则表达式
- (BOOL)baseCheckForRegEx:(NSString *)regEx data:(NSString *)data{
    
    //谓词查询
    NSPredicate *card = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
    // 判断是否匹配
    if (([card evaluateWithObject:data])) {
        return YES;
    }
    return NO;
}


#pragma mark  ====  回收键盘
- (void)hideKeyBoard{
    [self.mainTableView endEditing:YES];
}




#pragma mark =====   键盘弹出
- (void)keyboardWasShown:(NSNotification*)aNotification
{
   
    [self.backScrollView setContentSize:CGSizeMake(0,  selfPingMuHeight + 60 )];
}


#pragma mark =====   键盘消失
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [self.backScrollView setContentSize:CGSizeMake(0, 0)];
}




#pragma mark ====  移除所有通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




#pragma mark ====  懒加载
- (NSMutableArray *)MyArray{
    if (_MyArray == nil) {
        _MyArray = [NSMutableArray array];
    }
    return _MyArray;
}

// 背景 滚动scroller
- (UIScrollView *)backScrollView{
    
    if (_backScrollView == nil) {
        
        _backScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0,selfPingMuWidth, selfPingMuHeight - 60 )];
        
        self.backScrollView.backgroundColor = [UIColor whiteColor];
        
        self.backScrollView.delegate = self;
        
        self.backScrollView.showsVerticalScrollIndicator = NO;
        
        self.backScrollView.showsHorizontalScrollIndicator = NO;
        
        self.backScrollView.contentSize = CGSizeMake(0 , 0);
        
    }
    return _backScrollView;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
